/*
 * 归档页面组件 - Archives Page Component
 * 展示文章归档、时间线、分类统计等功能
 */

import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Spin, Empty, Collapse, Badge, Card, Typography, Statistic, Row, Col, Button } from 'antd';
import { CalendarOutlined, DownOutlined, RightOutlined, ArrowRightOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import SidebarTags from '@/components/SidebarTags';
import styles from './archives.less';
import { getArchivePosts } from '@/services/Post/api';
import { Post } from '@/models/post';

const { Panel } = Collapse;
const { Title, Text, Paragraph } = Typography;

interface ArchiveData {
  [year: number]: {
    [month: number]: Post[];
  };
}

const ArchivesPage: React.FC = () => {
  const [archiveData, setArchiveData] = useState<ArchiveData>({});
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedYears, setExpandedYears] = useState<string[]>([]);
  const [expandedMonths, setExpandedMonths] = useState<string[]>([]);
  const [selectedPost, setSelectedPost] = useState<Post | null>(null);
  const [isClosing, setIsClosing] = useState<boolean>(false);
  const [totalPosts, setTotalPosts] = useState<number>(0);

  // 获取归档数据
  useEffect(() => {
    const fetchArchiveData = async () => {
      try {
        setLoading(true);
        const response = await getArchivePosts();
        
        if (response.success && response.data) {
          setArchiveData(response.data);
          
          // 计算文章总数
          let count = 0;
          Object.values(response.data).forEach(yearData => {
            Object.values(yearData).forEach(monthPosts => {
              count += monthPosts.length;
            });
          });
          setTotalPosts(count);
          
          // 默认展开最新的年份和月份
          const years = Object.keys(response.data).sort((a, b) => Number(b) - Number(a));
          if (years.length > 0) {
            setExpandedYears([years[0]]);
            
            // 获取最新年份的月份并默认展开第一个月份
            const latestYear = years[0];
            const months = Object.keys(response.data[latestYear]).sort((a, b) => Number(b) - Number(a));
            if (months.length > 0) {
              setExpandedMonths([`${latestYear}-${months[0]}`]);
            }
          }
        } else {
          setError('获取归档数据失败');
        }
      } catch (error) {
        console.error('获取归档数据错误:', error);
        setError('获取归档数据失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchArchiveData();
  }, []);

  // 处理年份面板展开/折叠
  const handleYearChange = (keys: string | string[]) => {
    setExpandedYears(typeof keys === 'string' ? [keys] : keys);
  };
  
  // 处理月份面板展开/折叠
  const handleMonthChange = (keys: string | string[]) => {
    setExpandedMonths(typeof keys === 'string' ? [keys] : keys);
  };

  // 处理文章点击
  const handlePostClick = (post: Post) => {
    // 添加一个小延迟，让动画效果更自然
    setTimeout(() => {
      setSelectedPost(post);
    }, 50);
  };

  // 关闭文章预览
  const handleClosePreview = () => {
    setIsClosing(true);
    setTimeout(() => {
      setSelectedPost(null);
      setIsClosing(false);
    }, 300); // 动画持续时间为0.3秒，与CSS动画保持一致
  };

  // 跳转到文章详情页面
  const handleGoToDetail = (postId: number) => {
    history.push(`/post/${postId}`);
  };

  // 获取月份名称
  const getMonthName = (month: number) => {
    const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
    return monthNames[month - 1];
  };
  
  // 格式化日期，修复时区问题
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    // 使用 toISOString 获取 UTC 时间，然后只取日期部分
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };

  // 渲染加载状态
  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <Spin size="large" />
        <p>正在加载归档数据...</p>
      </div>
    );
  }

  // 渲染错误状态
  if (error) {
    return (
      <div className={styles.errorContainer}>
        <Empty description={error} />
      </div>
    );
  }

  // 渲染归档内容
  return (
    <PageContainer ghost>
      <div className={styles.headerImage}>
        <img src="https://iiiu-assets-images.oss-cn-beijing.aliyuncs.com/assets/test.jpg?Expires=1756307172&OSSAccessKeyId=TMP.3KtH5yADB6FBiLcodsY4PjZoRWiHAp7TX3bJSF8tsyY5b4bSveBbwYfjfMZyPLJJAWvoxb23EJfkPnsemai1fjLjnEWYF7&Signature=9MGG6ukYcKa%2BnlPmx3ptISYRxZU%3D" alt="文章归档" />
        <div className={styles.waveOverlay}></div>
      </div>
      <div className={`${styles.container} ${selectedPost ? styles.withPreview : ''}`}>
        <div className={styles.mainContent}>
          <div className={styles.archiveContent}>
            <div className={styles.archiveHeader}>
              <Title level={2}>文章归档</Title>
              <Statistic title="文章总数" value={totalPosts} />
            </div>
            
            {Object.keys(archiveData).length === 0 ? (
              <Empty description="暂无归档文章" />
            ) : (
              <div className={styles.timeline}>
                <Collapse 
                  accordion 
                  activeKey={expandedYears}
                  onChange={handleYearChange}
                  expandIcon={({ isActive }) => isActive ? <DownOutlined /> : <RightOutlined />}
                  className={styles.yearCollapse}
                >
                  {Object.entries(archiveData)
                    .sort(([yearA], [yearB]) => Number(yearB) - Number(yearA))
                    .map(([year, monthsData]) => {
                      // 计算当年文章总数
                      let yearPostCount = 0;
                      Object.values(monthsData).forEach(posts => {
                        yearPostCount += posts.length;
                      });
                      
                      return (
                        <Panel 
                          key={year} 
                          header={
                            <div className={styles.yearHeader}>
                              <span className={styles.yearTitle}>{year}年</span>
                              <span className={styles.yearCount}>共 {yearPostCount} 篇文章</span>
                            </div>
                          }
                          className={styles.yearPanel}
                        >
                          <Collapse
                            className={styles.monthCollapse}
                            expandIcon={({ isActive }) => isActive ? <DownOutlined /> : <RightOutlined />}
                            activeKey={expandedMonths}
                            onChange={handleMonthChange}
                          >
                            {Object.entries(monthsData)
                              .sort(([monthA], [monthB]) => Number(monthB) - Number(monthA))
                              .map(([month, posts]) => {
                                const monthKey = `${year}-${month}`;
                                return (
                                  <Panel
                                    key={monthKey}
                                    header={
                                      <div className={styles.monthHeader}>
                                        <CalendarOutlined className={styles.monthIcon} />
                                        <span className={styles.monthTitle}>{getMonthName(Number(month))}</span>
                                        <span className={styles.monthCount}>{posts.length} 篇</span>
                                      </div>
                                    }
                                    className={styles.monthPanel}
                                  >
                                    <div className={styles.postsGrid}>
                                      {posts.map(post => (
                                        <Card 
                                          key={post.id} 
                                          className={styles.postCard}
                                          onClick={() => handlePostClick(post)}
                                          hoverable
                                        >
                                          <div className={styles.postCardContent}>
                                            <div className={styles.postInfo}>
                                              <Title level={5} ellipsis={{ rows: 1 }} className={styles.postTitle}>
                                                {post.title}
                                              </Title>
                                              <div className={styles.postMeta}>
                                                <CalendarOutlined />
                                                <span>{formatDate(post.createTime)}</span>
                                              </div>
                                              <div className={styles.postContentPreview}>
                                                <Paragraph ellipsis={{ rows: 2 }} className={styles.postSummary}>
                                                  {post.content.replace(/<[^>]+>/g, '')}
                                                </Paragraph>
                                              </div>
                                            </div>
                                            <div className={styles.postImageContainer}>
                                              <div 
                                                className={styles.postImage}
                                                style={{ backgroundImage: `url(${post.coverImage || require('@/assets/images/post.png')})` }}
                                              />
                                            </div>
                                          </div>
                                        </Card>
                                      ))}
                                    </div>
                                  </Panel>
                                );
                              })}
                          </Collapse>
                        </Panel>
                      );
                    })}
                </Collapse>
              </div>
            )}
          </div>
          
          {/* 侧边栏 */}
          {!selectedPost && (
            <aside className={styles.sidebar}>
              <SidebarTags />
            </aside>
          )}
          
          {/* 文章预览 */}
          {selectedPost && (
            <div className={`${styles.postPreview} ${isClosing ? styles.postPreviewClosing : ''}`}>
              <div className={styles.previewHeader}>
                <Title level={3}>{selectedPost.title}</Title>
                <Text type="secondary">
                  发布于 {new Date(selectedPost.createTime).toLocaleDateString()}
                </Text>
                <button className={styles.closeButton} onClick={handleClosePreview}>
                  ×
                </button>
              </div>
              <div className={styles.previewContent}>
                <div dangerouslySetInnerHTML={{ __html: selectedPost.content }} />
              </div>
              <div className={styles.previewActions}>
                <Button 
                  type="primary" 
                  size="middle"
                  icon={<ArrowRightOutlined />}
                  onClick={() => handleGoToDetail(selectedPost.id)}
                  className={styles.goToDetailButton}
                  title="查看完整文章"
                >
                  查看详情
                </Button>
              </div>
            </div>
          )}
        </div>
      </div>
    </PageContainer>
  );
};

export default ArchivesPage;